package com.mdc.mansion.api.web.modules.system.web.account;

import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import com.google.common.collect.Lists;
import com.mdc.mansion.core.common.util.RestaurantSupport;
import com.mdc.mansion.dataaccess.modules.basedata.entity.RestaurantStaffReceiveDishes;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.mdc.mansion.api.web.common.interceptor.NoLoginCheck;
import com.mdc.mansion.api.web.common.utils.login.LoginTicket;
import com.mdc.mansion.api.web.common.utils.login.LoginUtil;
import com.mdc.mansion.api.web.common.web.BaseController;
import com.mdc.mansion.api.web.modules.system.bo.LoginUser;
import com.mdc.mansion.api.web.modules.system.bo.UserRegister;
import com.mdc.mansion.common.exception.BusinessException;
import com.mdc.mansion.common.response.Result;
import com.mdc.mansion.common.response.ResultCode;
import com.mdc.mansion.common.util.I18nUtil;
import com.mdc.mansion.component.cache.common.util.CacheUtil;
import com.mdc.mansion.core.common.sms.SendMobileService;
import com.mdc.mansion.core.modules.restaurant.AccountService;
import com.mdc.mansion.core.modules.restaurant.RestaurantService;
import com.mdc.mansion.core.modules.restaurant.RestaurantStaffService;
import com.mdc.mansion.dataaccess.modules.restaurant.entity.Restaurant;
import com.mdc.mansion.dataaccess.modules.restaurant.entity.RestaurantStaff;

/**
 * <p>
 * com.mdc.mansion.api.web.modules.system.web.register.RegisterController
 * </p>
 * <p>
 * Title: RegisterController
 * </p>
 * Copyright: Copyright © 2010-2014
 * </p>
 * <p>
 * Company: jumei
 * </p>
 * @author xiang.liu
 * @version 1.0
 */
@RequestMapping("${adminPath}/account")
@Controller
public class AccountController extends BaseController {
    @Resource
    private AccountService accountService;
    @Resource
    private RestaurantStaffService restaurantStaffService;
    @Resource
    private SendMobileService sendMobileService;
    @Resource
    private RestaurantService restaurantService;
    private final static String VERIFY_CODE = "VERIFY_CODE";
    private final static String SEARCH_PASSWORD = "SEARCH_PASSWORD";
    /**
     * 生成验证码
     * @author liuxiang
     * @date create_time：2018年1月3日 上午12:20:54
     * @return
     */
    @NoLoginCheck
    @RequestMapping("/getCharCode")
    public Result getCode() {
        int codeCount = 4;// 定义图片上显示验证码的个数
        char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        Result result = new Result(ResultCode.COMMON_SUCCESS);
        Random random = new Random();
        StringBuffer randomCode = new StringBuffer();
        for (int i = 0; i < codeCount; i++) {
            String code = String.valueOf(codeSequence[random.nextInt(codeSequence.length - 1)]);
            randomCode.append(code);
        }
        
        String codeId = System.currentTimeMillis() + "" + randomCode.subSequence(0, 2) + random.nextInt(1000);
        // 加入缓存中 下一次登录的时候验证
        CacheUtil.hset(VERIFY_CODE + codeId, codeId, randomCode.toString(), 3600);
        result.setProperty("codeId", codeId);
        result.setProperty("code", randomCode);
        return result;
    }
    /**
     * 生成短信验证码
     * @author liuxiang
     * @date create_time：2018年1月3日 上午12:20:54
     * @return
     */
    @NoLoginCheck
    @RequestMapping("/forgetPasswordSmsCode")
    public Result forgetPasswordSmsCode(String data) {
        JSONObject obj = JSONObject.parseObject(data);
        String loginAccount = obj.getString("loginAccount");
        RestaurantStaff staff = restaurantStaffService.findByLoginAccount(loginAccount);
        if(staff == null){
            throw new BusinessException(I18nUtil.getMessage("account.notexist",loginAccount));// 账户不存在
        }
        int codeCount = 4;// 定义图片上显示验证码的个数
        char[] codeSequence = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        Result result = new Result(ResultCode.COMMON_SUCCESS);
        Random random = new Random();
        StringBuffer randomCode = new StringBuffer();
        for (int i = 0; i < codeCount; i++) {
            String code = String.valueOf(codeSequence[random.nextInt(codeSequence.length - 1)]);
            randomCode.append(code);
        }
        
        String codeId = System.currentTimeMillis() + "" + randomCode.subSequence(0, 2) + random.nextInt(1000);
        // 发生短信验证码
        String countryCode = staff.getCountryCode();
        String phone = staff.getTel();
        sendMobileService.sendSmsCode(countryCode, phone, randomCode.toString());
        // 加入缓存中 下一次登录的时候验证
        CacheUtil.hset(SEARCH_PASSWORD + codeId, codeId, randomCode.toString() + loginAccount, 300);
        result.setProperty("codeId", codeId);
        return result;
    }
    @NoLoginCheck
    @RequestMapping("/checkForgetPasswordSmsCode")
    public Result checkForgetPasswordSmsCode(String data) {
        Result result = new Result(ResultCode.COMMON_SUCCESS);
        JSONObject obj = JSONObject.parseObject(data);
        String smsCode = obj.getString("smsCode");
        String codeId = obj.getString("codeId");
        String codeCache = CacheUtil.hget(SEARCH_PASSWORD+codeId, codeId,String.class); 
        if(codeCache == null){
            throw new BusinessException(I18nUtil.getMessage("verification.code.error"));// 验证码错误
        }
        String code = codeCache.substring(0,4);
        if(!code.equals(smsCode)){
            throw new BusinessException(I18nUtil.getMessage("verification.code.error"));// 验证码错误
        }
        result.setProperty("loginAccount", codeCache.substring(4));
        return result;
    }
    @NoLoginCheck
    @RequestMapping("/forgetResetPassword")
    public Result forgetResetPassword(String data){
        Result result = new Result(ResultCode.COMMON_SUCCESS);
        JSONObject obj = JSONObject.parseObject(data);
        String loginAccount = obj.getString("loginAccount");
        String newPassword = obj.getString("newPassword");
        String confirmPassword = obj.getString("confirmPassword");
        if(!newPassword.equals(confirmPassword)){
            throw new BusinessException(I18nUtil.getMessage("register.password.not.same"));// 两次密码不一致
        }
        accountService.forgetResetPassword(loginAccount, newPassword);
        return result;
    }
    /**
     * 注册
     * @author liuxiang
     * @date create_time：2018年1月3日 上午12:34:01
     * @param data
     * @return
     */
    @NoLoginCheck
    @RequestMapping("/register")
    public Result register(String data){
        Result result = new Result(ResultCode.COMMON_SUCCESS);
        UserRegister userRegister = JSONObject.parseObject(data, UserRegister.class);
        // 验证两个密码是否一致
        if(!userRegister.getPassword().equals(userRegister.getConfirmPassword())){
            throw new BusinessException(I18nUtil.getMessage("register.password.not.same"));// 两次密码不匹配
        }
        String verifyCode = userRegister.getVerifyCode();
        // 验证验证码是否一致
        String codeId = userRegister.getCodeId();
        // 缓存中获取验证码
        String code = CacheUtil.hget(VERIFY_CODE+codeId, codeId,String.class);
        if(code == null){
            throw new BusinessException(I18nUtil.getMessage("verification.code.error"));// 验证码错误
        }
        if(!verifyCode.equalsIgnoreCase(code.toString())){
            throw new BusinessException(I18nUtil.getMessage("verification.code.error"));// 验证码错误
        }
        accountService.register(userRegister.getLoginAccount(), userRegister.getPassword(), userRegister.getTel(),userRegister.getCountryCode());
        return result;
    }
    /**
     * 登录
     * @author 刘想
     * @date create_time：2018年1月3日 上午12:34:17
     * @return
     */
    @NoLoginCheck
    @RequestMapping("/login")  
    public Result login(String data){
        Result result = new Result(ResultCode.COMMON_SUCCESS);
        LoginUser loginUser= JSONObject.parseObject(data,LoginUser.class);
        String loginAccount=loginUser.getLoginAccount();
        String password = loginUser.getPassword();
        RestaurantStaff staff = accountService.login(loginAccount, password);
        String restaurantId = staff.getRestaurantId();
        // 登录认证完毕 开始计算ticket信息
        LoginTicket loginTicket = LoginUtil.createUserLoginTicket(loginAccount);
        LoginUtil.putLoginTicketInCache(loginTicket);
        String token = loginTicket.getToken();
        result.setProperty("token", token);
        result.setProperty("roleType", staff.getRoleType());
        result.setProperty("loginAccount", staff.getLoginAccount());
        result.setProperty("restaurantId", restaurantId);
        List<String> tags= Lists.newArrayList();
        tags.add(RestaurantSupport.createJpushTag(restaurantId,staff.getRoleType()));
        tags.add(RestaurantSupport.createJpushTag(restaurantId,""));
        result.setProperty("tags", tags);
        String name = "";
        String englishName = "";
        String chineseName = "";
        if(restaurantId!=null&&!"".equals(restaurantId)){
            Restaurant restaurant = restaurantService.get(restaurantId);
            if(restaurant!=null){
                name = restaurant.getName();
                englishName = restaurant.getEnglishName();
                chineseName = restaurant.getChineseName();
            }
        }
        result.setProperty("name", name);
        result.setProperty("englishName", englishName);
        result.setProperty("chineseName", chineseName);
        return result;
    }
    /**
     * 登出
     * @author liuxiang
     * @date create_time：2018年1月3日 上午12:34:35
     * @param token
     * @return
     */
    @RequestMapping("/loginOut")  
    public Result loginOut(String token){
        Result result = new Result(ResultCode.COMMON_SUCCESS);
        LoginTicket loginTicket = LoginUtil.getLoginTicketByToken(token);
        if(loginTicket!=null){
            LoginUtil.removeTicketFromCache(loginTicket);
        }
        return result;
    }
    @RequestMapping("/changePassword")  
    public Result changePassword(String token,String data){
        Result result = new Result(ResultCode.COMMON_SUCCESS);
        JSONObject obj = JSONObject.parseObject(data);
        String oldPassword = obj.getString("oldPassword");
        String newPassword = obj.getString("newPassword");
        String confirmPassword = obj.getString("confirmPassword");
        if(!newPassword.equals(confirmPassword)){
            throw new BusinessException(I18nUtil.getMessage("register.password.not.same"));// 两次密码不一致
        }
        accountService.changePassword(oldPassword, newPassword);
        // 修改完毕 清除原来登录信息
        LoginTicket loginTicket = LoginUtil.getLoginTicketByToken(token);
        if(loginTicket!=null){
            LoginUtil.removeTicketFromCache(loginTicket);
        }
        return result;
    }
    
    
}
